<script setup lang="ts" name="ExcelExportDialog">
import { useResizeObserver, useDebounceFn } from '@vueuse/core'
import { storeToRefs } from 'pinia'
import draggable from 'vuedraggable'
import { DEF_FILE_NAME } from './helper'
import { useAppStoreWithOut } from '@/store/modules/app'

const appStore = useAppStoreWithOut()
const { systemConfig } = storeToRefs(appStore)
const { t } = useI18n() // 国际化

const dialogVisible = ref(false)

const props = defineProps({
  fieldList: { type: Array as any },
  hasSelected: { type: Boolean }
})

// 打开弹窗
const handleOpenDialog = () => {
  dialogVisible.value = true
  setTimeout(() => {
    getModalHeight()
  }, 200)
}
// 关闭弹窗
const handleCloseDialog = () => {
  dialogVisible.value = false
}
// 子组件将方法暴露给父组件
defineExpose({ handleOpenDialog })

// 最大化效果
const fullscreen = ref(false)
// 最大化点击事件
const maxSizeHandle = () => {
  fullscreen.value = !fullscreen.value
}
// 监听最大化事件
watch(
  () => fullscreen.value,
  () => {
    getModalHeight()
  }
)
const modalHeight = ref(0)
// 监听元素尺寸变化
useResizeObserver(
  document.body,
  useDebounceFn(() => {
    getModalHeight()
  }, 200)
)
const modalHeader = ref<HTMLElement | null>(null)
const modalFooter = ref<HTMLElement | null>(null)
// 获取当前的表格的最大高度
const getModalHeight = () => {
  if (dialogVisible.value) {
    const rect = document.body.getBoundingClientRect()
    if (modalHeader.value && modalFooter.value) {
      if (fullscreen.value) {
        modalHeight.value = rect.height - modalHeader.value.offsetHeight - modalFooter.value.offsetHeight - 15 * 2 - systemConfig.value.space * 2 - 2
      } else {
        modalHeight.value = rect.height * 0.7 - modalHeader.value.offsetHeight - modalFooter.value.offsetHeight - 15 * 2 - systemConfig.value.space * 2 - 2
      }
    }
  }
}

const emit = defineEmits(['success'])

const handleOk = () => {
  const sortArr: any = []
  const headerObj = {}
  fieldsList.value.forEach((item: any) => {
    if (checkedFields.value.includes(item.key)) {
      sortArr.push(item.key)
      headerObj[item.key] = item.value
    }
  })
  emit('success', {
    filename: `${exportInfo.value.filename === '' ? DEF_FILE_NAME.split('.')[0] : exportInfo.value.filename}.${exportInfo.value.fileType}`,
    fileType: exportInfo.value.fileType,
    dataScope: exportInfo.value.dataScope,
    header: headerObj,
    sort: sortArr,
    headerType: exportInfo.value.headerType
  })
  handleCloseDialog()
}

const exportInfo = ref({
  filename: '',
  fileType: 'xlsx',
  dataScope: 1,
  headerType: 'default'
})

const checkAllField = ref(false)
const isIndeterminate = ref(false)
const checkedFields: any = ref([])
const fieldsList = ref(props.fieldList || [])

const handleCheckAllChange = (val: boolean) => {
  checkedFields.value = []
  fieldsList.value.forEach((item) => {
    if (val) {
      checkedFields.value.push(item.key)
    }
  })
  isIndeterminate.value = false
  console.log(checkedFields.value)
}
const handleCheckedFieldsChange = (value: string[]) => {
  const checkedCount = value.length
  checkAllField.value = checkedCount === props.fieldList.length
  isIndeterminate.value = checkedCount > 0 && checkedCount < props.fieldList.length
  console.log(checkedFields.value)
}
</script>

<template>
  <ElDialog v-model="dialogVisible" width="600px" append-to-body destroy-on-close :fullscreen="fullscreen" :show-close="false" :before-close="handleCloseDialog">
    <template #header>
      <div ref="modalHeader" class="modal-header">
        <div class="header-title">{{ t('export', 'title') }}</div>
        <ElTooltip :content="fullscreen ? t('common', 'restoreDown') : t('common', 'maximize')" placement="bottom">
          <ElButton size="small" @click="maxSizeHandle"><SvgIcon :icon="fullscreen ? 'bi:fullscreen-exit' : 'bi:fullscreen'" /></ElButton>
        </ElTooltip>
        <ElTooltip :content="t('action', 'close')" placement="bottom">
          <ElButton size="small" @click="handleCloseDialog"><SvgIcon icon="ep:close" /></ElButton>
        </ElTooltip>
      </div>
    </template>
    <div class="export-modal__body">
      <ElScrollbar :style="{ height: modalHeight + 'px' }">
        <ElForm>
          <ElFormItem :label="t('export', 'fileName')" prop="filename">
            <ElInput v-model="exportInfo.filename" clearable />
          </ElFormItem>
          <ElFormItem :label="t('export', 'fileType')">
            <ElSelect v-model="exportInfo.fileType" placeholder="">
              <ElOption :label="t('export', 'fileTypeXlsx')" value="xlsx" />
              <ElOption :label="t('export', 'fileTypeCsv')" value="csv" />
              <ElOption :label="t('export', 'fileTypeHtml')" value="html" />
              <ElOption :label="t('export', 'fileTypeXml')" value="xml" />
              <ElOption :label="t('export', 'fileTypeTxt')" value="txt" />
            </ElSelect>
          </ElFormItem>
          <ElFormItem :label="t('export', 'dataScope')">
            <ElSelect v-model="exportInfo.dataScope" placeholder="">
              <ElOption :label="t('export', 'dataScopeCurrentPage')" :value="1" />
              <ElOption :label="t('export', 'dataScopeSelected')" :value="2" :disabled="!props.hasSelected" />
              <ElOption :label="t('export', 'dataScopeAll')" :value="3" />
            </ElSelect>
          </ElFormItem>
          <ElFormItem :label="t('export', 'headerType')">
            <ElRadioGroup v-model="exportInfo.headerType" class="radio-button">
              <ElRadioButton label="default">{{ t('export', 'headerTypeDefault') }}</ElRadioButton>
              <ElRadioButton label="custom">{{ t('export', 'headerTypeCustom') }}</ElRadioButton>
            </ElRadioGroup>
          </ElFormItem>
          <ElFormItem :label="t('export', 'fields')">
            <div class="field-list flex-1 m-6px">
              <div class="all-field">
                <ElCheckbox v-model="checkAllField" :indeterminate="isIndeterminate" @change="handleCheckAllChange">
                  {{ t('export', 'allFields') }}
                </ElCheckbox>
              </div>
              <ElCheckboxGroup v-model="checkedFields" @change="handleCheckedFieldsChange">
                <draggable :list="fieldsList" :item-key="(key) => key" animation="300" handle=".move">
                  <template #item="{ element }">
                    <div class="item-field">
                      <span class="move"><svg-icon icon="ri:drag-move-2-fill" /></span>
                      <ElCheckbox :label="element.key">{{ element.value }}</ElCheckbox>
                    </div>
                  </template>
                </draggable>
              </ElCheckboxGroup>
            </div>
          </ElFormItem>
        </ElForm>
      </ElScrollbar>
    </div>
    <template #footer>
      <span ref="modalFooter" class="modal-footer">
        <ElButton @click="handleCloseDialog">{{ t('action', 'cancel') }}</ElButton>
        <ElButton type="primary" @click="handleOk">{{ t('action', 'confirm') }}</ElButton>
      </span>
    </template>
  </ElDialog>
</template>

<style scoped lang="scss">
.modal-header {
  display: flex;
  padding: 15px var(--el-space);
  margin: -15px calc(0px - var(--el-space));

  .header-title {
    flex: 1;
    height: 24px;
    line-height: 24px;
  }

  .el-button {
    margin-left: 0;
    background: none !important;
    border: none !important;

    &:hover,
    &:focus {
      background: none;
    }
  }
}

.modal-footer {
  display: inline-flex;
  overflow: hidden;
}

.el-dialog {
  :deep(.el-dialog__body) {
    padding: 0;
  }
}

.export-modal__body {
  margin: calc(0px - var(--el-space));
  overflow: hidden;

  :deep(.el-scrollbar__view) {
    padding: var(--el-space);
  }
}

.field-list {
  border: 1px solid var(--el-border-color-lighter);

  .all-field {
    padding-left: 36px;
    background: var(--el-fill-color-light);
    border-bottom: 1px solid var(--el-border-color-lighter);
  }

  .el-checkbox-group {
    padding: 6px 0;
  }

  .item-field {
    display: flex;
    align-items: center;

    .move {
      padding: 0 10px;
      font-size: 14px;
      cursor: move;

      .el-icon {
        color: var(--el-text-color-secondary);
      }
    }
  }
}
</style>
